﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Collections.Specialized;
using System.Diagnostics;

using MySql;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Web.Configuration;
using System.Data;

namespace doris.Admin {
    public partial class UpdateUser : System.Web.UI.Page {
        DorisMembershipProvider Membership;
        DorisRoleProvider Role;
        MembershipCreateStatus status;
        MembershipUserCollection myuser;
        int currCompanyID;

        protected void Page_Load(object sender, EventArgs e) {
            Membership = new DorisMembershipProvider();
            Role = new DorisRoleProvider();

            NameValueCollection config = new NameValueCollection();
            config.Add("name","DorisMembershipProvider");
            config.Add("type","DorisMembershipProvider");
            config.Add("applicationName", "/");
            config.Add("connectionStringName", "localConnectionString");

            Membership.Initialize("DorisMembershipProvider", config);
            Role.Initialize("DorisRoleProvider", config);
            status = new MembershipCreateStatus();

            myuser = Membership.GetAllUsers();

            currCompanyID = GetCompanies();

        if (Request.QueryString["Id"] != null)
        {
            if (!IsPostBack)
            {
                string userName = Request.QueryString["Id"].ToString();

                MembershipUser Current = myuser[userName];
               
                UsernameLabel.Text = Current.UserName;
                EmailText.Text = Current.Email;
                CommentTextBox.Text = Current.Comment;
                IsApprovedCheck.Checked = Current.IsApproved;
                IsLockedOutCheck.Checked = Current.IsLockedOut;

                //                lblPassword.Text = Current.GetPassword();
                ListItem li;
                String[] allRoles = Role.GetAllRoles();
                String[] roles = Role.GetRolesForUser(userName);
                for (int i = 0; i < allRoles.Count(); i++) {
                    li = new ListItem(allRoles[i]);
                    for (int j = 0; j < roles.Count(); j++) {
                        if (roles[j] == allRoles[i]) {
                            li.Selected = true;
                        }
                    }
                    roller.Items.Add(li);
                }
            }
        }

    }

        protected void StoreCompany(int CompanyID) {
            Debug.WriteLine("StoreCompany - " + CompanyID);
            MySqlConnection conn = new MySqlConnection(WebConfigurationManager.ConnectionStrings["localConnectionString"].ConnectionString);
            try {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;

                cmd.CommandText = "storeUsersCompany";
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add(new MySqlParameter("@in_username", MySqlDbType.VarChar));
                cmd.Parameters["@in_username"].Value = Request.QueryString["Id"].ToString();
                cmd.Parameters["@in_username"].Direction = ParameterDirection.Input;

                cmd.Parameters.Add(new MySqlParameter("@in_companyid", MySqlDbType.Int32));
                if (CompanyID == 0) 
                    cmd.Parameters["@in_companyid"].Value = null;
                else
                    cmd.Parameters["@in_companyid"].Value = CompanyID;
                cmd.Parameters["@in_companyid"].Direction = ParameterDirection.Input;

                Debug.WriteLine("ran");

                cmd.ExecuteNonQuery();
            } finally {
                conn.Close();
            }
        }

    protected int GetCompanies() {
        int currCompanyID = 0;
            MySqlConnection conn = new MySqlConnection(WebConfigurationManager.ConnectionStrings["localConnectionString"].ConnectionString);
            try {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;

                cmd.CommandText = "getUserByUsername";
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add(new MySqlParameter("@in_username", MySqlDbType.VarChar));
                cmd.Parameters["@in_username"].Value = Request.QueryString["Id"].ToString();
                cmd.Parameters["@in_username"].Direction = ParameterDirection.Input;

                MySqlDataReader reader = cmd.ExecuteReader();

                if (reader.Read()) {
                    if (reader["CompanyID"].ToString() != "")
                        currCompanyID = int.Parse(reader["CompanyID"].ToString());
                }

            } finally {
                conn.Close();
            }

            conn = new MySqlConnection(WebConfigurationManager.ConnectionStrings["localConnectionString"].ConnectionString);
            try {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;

                cmd.CommandText = "getAllCompanies";
                cmd.CommandType = CommandType.StoredProcedure;

                MySqlDataReader reader = cmd.ExecuteReader();

                while (reader.Read()) {
                    ListItem li = new ListItem(reader["Name"].ToString(), reader["CompanyID"].ToString());
                    if (int.Parse(reader["CompanyID"].ToString()) == currCompanyID) 
                        li.Selected = true;
                    ddFirma.Items.Add(li);
                }



            } finally {
                conn.Close();
            }
            return currCompanyID;
        }

    //-- Update button
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            string userName = Request.QueryString["Id"].ToString();
            MembershipUser Current = myuser[userName];
            Current.Email = EmailText.Text;
            Current.Comment = CommentTextBox.Text;
            Current.IsApproved = IsApprovedCheck.Checked;

            Membership.UpdateUser(Current);
            StoreCompany(int.Parse(ddFirma.SelectedValue));
            String[] allRoles = Role.GetAllRoles();
            String[] roles = Role.GetRolesForUser(userName);
            String[] users = {userName};
            List<String> toRoles = new List<String>();
            List<String> offRoles = new List<String>();

            Debug.WriteLine("Total: " + roller.Items.Count);

            for (int i = 0; i < roller.Items.Count; i++) {
                Debug.WriteLine("ID: " + i + ": " + roller.Items[i]);
                if (roller.Items[i].Selected) {
                    if (!Role.IsUserInRole(userName, allRoles[i])) {
                        Debug.WriteLine("ADD " + allRoles[i] + " TO " + userName);
                        toRoles.Add(allRoles[i]);
                    }
                } else {
                    Debug.WriteLine("count2: " + i + ": " + roles.Count());
                    if (Role.IsUserInRole(userName, allRoles[i])) {
                        Debug.WriteLine("REMOVE " + allRoles[i] + " FROM " + userName);
                        offRoles.Add(allRoles[i]);
                    }                    
                }
            }

            if (toRoles.Count() > 0) 
                Role.AddUsersToRoles(users, toRoles.ToArray());
            if (offRoles.Count() > 0)
                Role.RemoveUsersFromRoles(users, offRoles.ToArray());
            /*            for (int i = 0; i < allRoles.Count(); i++) {
                            for (int j = 0; j < roles.Count(); j++) {
                            }
                        }
                        */
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {
            Response.Redirect("~/Admin/ListUsers.aspx");
        }
    }    
    }
}